#include "app_mqtt.h"

rece_cb rece_call_back;

// 客户端
static MQTTClient client;
// 消息对象
static MQTTClient_message pubmsg = MQTTClient_message_initializer;
// 连接参数
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;

/**
 * 发布消息完成的回调函数
 */
void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_info("消息发布完成!");
}

/**
 * 接收到数据的回调函数
 */
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    if (rece_call_back != NULL)
    {
        log_info("接收到数据为%s", message->payload);
        rece_call_back(message->payload);
    }
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return 1;
}

/**
 * 连接断开的回调函数
 */
void connlost(void *context, char *cause)
{
    log_error("连接断开,原因是:%s", cause);
}

/**
 * @brief MQTT客户端的初始化
 */
int app_mqtt_init(rece_cb call_back)
{
    // 自定义回调函数接收
    rece_call_back = call_back;

    // 创建客户端
    if (MQTTClient_create(&client,
                          ADDRESS,
                          CLIENTID,
                          MQTTCLIENT_PERSISTENCE_NONE,
                          NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT客户端创建失败!");
        return -1;
    }

    // 注册回调函数
    if (MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT客户端注册回调函数失败!");
        MQTTClient_destroy(&client);
        return -1;
    }

    // 连接服务器
    if (MQTTClient_connect(client, &conn_opts) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT客户端连接服务器失败!");
        MQTTClient_destroy(&client);
        return -1;
    }

    // 订阅主题
    if (MQTTClient_subscribe(client, TOPIC_PULL, QOS) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT客户端订阅主题失败!");
        MQTTClient_disconnect(client, TIMEOUT);
        MQTTClient_destroy(&client);
        return -1;
    }

    return 0;
}

/**
 * 发布消息
 */
int app_mqtt_send(char *json_str)
{
    pubmsg.payload = json_str;
    pubmsg.payloadlen = (int)strlen(json_str);
    pubmsg.qos = QOS;
    if (MQTTClient_publishMessage(client, TOPIC_PUSH, &pubmsg, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("发布消息h失败!");
        return -1;
    }

    return 0;
}